#include "Buffer.h"
#include <errno.h>
#include <sys/uio.h>
#include <unistd.h>

ssize_t Buffer::readFd(int fd, int *saveErrno)
{
    char extrabuf[65536] = {0}; // 64k
    struct iovec vec[2];
    const size_t writable = writableBytes(); // 缓冲区剩余的可写空间
    vec[0].iov_base = beginWrite();
    vec[0].iov_len = writable;
    vec[1].iov_base = extrabuf;
    vec[1].iov_len = sizeof(extrabuf);

    const int iovcnt = (writable < sizeof(extrabuf) ? 2 : 1);
    const ssize_t n = ::readv(fd, vec, iovcnt);
    if (n < 0)
    {
        *saveErrno = errno;
    }
    else if (static_cast<size_t>(n) <= writable)
    {
        writerIndex_ += n;
    }
    else // extrabuf 里面写入了数据
    {
        writerIndex_ = buffer_.size();
        append(extrabuf, n - writable); // 把extrabuf的内容放入buffer_
    }
    return n;
}
